package com.zzyl.intercept;

import cn.hutool.core.map.MapUtil;
import com.zzyl.constant.Constants;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.properties.JwtTokenManagerProperties;
import com.zzyl.utils.JwtUtil;
import com.zzyl.utils.ObjectUtil;
import com.zzyl.utils.StringUtils;
import com.zzyl.utils.UserThreadLocal;
import io.jsonwebtoken.Claims;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Component
@RequiredArgsConstructor
public class UserInterceptor implements HandlerInterceptor {
    private final JwtTokenManagerProperties jwtTokenManagerProperties;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerInterceptor){
            throw new BaseException(BasicEnum.SYSYTEM_FAIL);
        }
        String token = request.getHeader(Constants.USER_TOKEN);
        if (ObjectUtil.isEmpty(token)){
            throw new BaseException(BasicEnum.LOGIN_LOSE_EFFICACY);
        }
        Claims claims = JwtUtil.parseJWT(jwtTokenManagerProperties.getBase64EncodedSecretKey(), token);
        if (ObjectUtil.isEmpty(claims)){
            throw new BaseException(BasicEnum.LOGIN_LOSE_EFFICACY);
        }
        Long userId = MapUtil.get(claims, Constants.JWT_USERID, Long.class);
        if (ObjectUtil.isEmpty(userId)){
            throw new BaseException(BasicEnum.LOGIN_LOSE_EFFICACY);
        }
        UserThreadLocal.set(userId);
        return true;



    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadLocal.remove();
    }
}
